﻿// MedicalRulesEngine.Core/Services/MetadataService.cs
using AutoMapper;
using Microsoft.Extensions.Logging;
using MedicalRulesEngine.Core.DTOs;
using MedicalRulesEngine.Domain.Entities;
using MedicalRulesEngine.Infrastructure.Repositories;
using System.Text.Json;

namespace MedicalRulesEngine.Core.Services;

/// <summary>
/// 元数据服务实现
/// 提供字段定义、操作符定义等元数据管理功能
/// </summary>
public class MetadataService : IMetadataService
{
    private readonly IRepository<FieldDefinition> _fieldRepository;
    private readonly IRepository<OperatorDefinition> _operatorRepository;
    private readonly IMapper _mapper;
    private readonly ILogger<MetadataService> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="fieldRepository">字段定义仓储</param>
    /// <param name="operatorRepository">操作符定义仓储</param>
    /// <param name="mapper">对象映射器</param>
    /// <param name="logger">日志记录器</param>
    public MetadataService(
        IRepository<FieldDefinition> fieldRepository,
        IRepository<OperatorDefinition> operatorRepository,
        IMapper mapper,
        ILogger<MetadataService> logger)
    {
        _fieldRepository = fieldRepository ?? throw new ArgumentNullException(nameof(fieldRepository));
        _operatorRepository = operatorRepository ?? throw new ArgumentNullException(nameof(operatorRepository));
        _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// 获取所有字段定义
    /// </summary>
    /// <returns>字段定义集合</returns>
    public async Task<IEnumerable<FieldDefinitionDto>> GetAllFieldDefinitionsAsync()
    {
        try
        {
            _logger.LogInformation("开始获取所有字段定义");

            var fieldDefinitions = await _fieldRepository.GetAllAsync();
            var fieldDtos = _mapper.Map<IEnumerable<FieldDefinitionDto>>(fieldDefinitions);

            // 解析支持的操作符JSON
            foreach (var fieldDto in fieldDtos)
            {
                var fieldEntity = fieldDefinitions.FirstOrDefault(f => f.Id == fieldDto.Id);
                if (fieldEntity != null && !string.IsNullOrWhiteSpace(fieldEntity.SupportedOperatorsJson))
                {
                    try
                    {
                        fieldDto.SupportedOperators = JsonSerializer.Deserialize<List<string>>(fieldEntity.SupportedOperatorsJson) ?? new List<string>();
                    }
                    catch (JsonException ex)
                    {
                        _logger.LogWarning(ex, "解析字段 {FieldName} 的支持操作符JSON失败", fieldEntity.Name);
                        fieldDto.SupportedOperators = new List<string>();
                    }
                }
            }

            _logger.LogInformation("成功获取 {Count} 个字段定义", fieldDtos.Count());
            return fieldDtos.OrderBy(f => f.Category).ThenBy(f => f.Order);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取所有字段定义时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 根据分类获取字段定义
    /// </summary>
    /// <param name="category">分类</param>
    /// <returns>字段定义集合</returns>
    public async Task<IEnumerable<FieldDefinitionDto>> GetFieldDefinitionsByCategoryAsync(string category)
    {
        try
        {
            _logger.LogInformation("开始获取分类字段定义，Category: {Category}", category);

            var fieldDefinitions = await _fieldRepository.FindAsync(f => f.Category == category);
            var fieldDtos = _mapper.Map<IEnumerable<FieldDefinitionDto>>(fieldDefinitions);

            // 解析支持的操作符JSON
            foreach (var fieldDto in fieldDtos)
            {
                var fieldEntity = fieldDefinitions.FirstOrDefault(f => f.Id == fieldDto.Id);
                if (fieldEntity != null && !string.IsNullOrWhiteSpace(fieldEntity.SupportedOperatorsJson))
                {
                    try
                    {
                        fieldDto.SupportedOperators = JsonSerializer.Deserialize<List<string>>(fieldEntity.SupportedOperatorsJson) ?? new List<string>();
                    }
                    catch (JsonException ex)
                    {
                        _logger.LogWarning(ex, "解析字段 {FieldName} 的支持操作符JSON失败", fieldEntity.Name);
                        fieldDto.SupportedOperators = new List<string>();
                    }
                }
            }

            _logger.LogInformation("成功获取分类 {Category} 的 {Count} 个字段定义", category, fieldDtos.Count());
            return fieldDtos.OrderBy(f => f.Order);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取分类字段定义时发生错误，Category: {Category}", category);
            throw;
        }
    }

    /// <summary>
    /// 获取所有操作符定义
    /// </summary>
    /// <returns>操作符定义集合</returns>
    public async Task<IEnumerable<OperatorDefinitionDto>> GetAllOperatorDefinitionsAsync()
    {
        try
        {
            _logger.LogInformation("开始获取所有操作符定义");

            var operatorDefinitions = await _operatorRepository.GetAllAsync();
            var operatorDtos = _mapper.Map<IEnumerable<OperatorDefinitionDto>>(operatorDefinitions);

            // 解析支持的数据类型JSON
            foreach (var operatorDto in operatorDtos)
            {
                var operatorEntity = operatorDefinitions.FirstOrDefault(o => o.Id == operatorDto.Id);
                if (operatorEntity != null && !string.IsNullOrWhiteSpace(operatorEntity.SupportedDataTypesJson))
                {
                    try
                    {
                        operatorDto.SupportedDataTypes = JsonSerializer.Deserialize<List<string>>(operatorEntity.SupportedDataTypesJson) ?? new List<string>();
                    }
                    catch (JsonException ex)
                    {
                        _logger.LogWarning(ex, "解析操作符 {OperatorCode} 的支持数据类型JSON失败", operatorEntity.Code);
                        operatorDto.SupportedDataTypes = new List<string>();
                    }
                }
            }

            _logger.LogInformation("成功获取 {Count} 个操作符定义", operatorDtos.Count());
            return operatorDtos.OrderBy(o => o.Category).ThenBy(o => o.Order);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取所有操作符定义时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 根据数据类型获取支持的操作符
    /// </summary>
    /// <param name="dataType">数据类型</param>
    /// <returns>操作符定义集合</returns>
    public async Task<IEnumerable<OperatorDefinitionDto>> GetOperatorsByDataTypeAsync(string dataType)
    {
        try
        {
            _logger.LogInformation("开始获取数据类型支持的操作符，DataType: {DataType}", dataType);

            var allOperators = await GetAllOperatorDefinitionsAsync();
            var supportedOperators = allOperators.Where(o =>
                o.SupportedDataTypes.Contains(dataType) ||
                o.SupportedDataTypes.Contains("*"));

            _logger.LogInformation("数据类型 {DataType} 支持 {Count} 个操作符", dataType, supportedOperators.Count());
            return supportedOperators.OrderBy(o => o.Order);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取数据类型支持的操作符时发生错误，DataType: {DataType}", dataType);
            throw;
        }
    }

    /// <summary>
    /// 获取规则编辑器配置
    /// </summary>
    /// <returns>编辑器配置</returns>
    public async Task<RuleEditorConfig> GetRuleEditorConfigAsync()
    {
        try
        {
            _logger.LogInformation("开始获取规则编辑器配置");

            var config = new RuleEditorConfig
            {
                FieldDefinitions = (await GetAllFieldDefinitionsAsync()).ToList(),
                OperatorDefinitions = (await GetAllOperatorDefinitionsAsync()).ToList(),
                DataTypes = GetDataTypeDefinitions(),
                ActionTypes = GetActionTypeDefinitions(),
                Priorities = GetPriorityDefinitions(),
                Categories = GetCategoryDefinitions()
            };

            _logger.LogInformation("成功获取规则编辑器配置");
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取规则编辑器配置时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 初始化默认元数据
    /// </summary>
    public async Task InitializeDefaultMetadataAsync()
    {
        try
        {
            _logger.LogInformation("开始初始化默认元数据");

            // 检查是否已经初始化
            var existingFields = await _fieldRepository.CountAsync();
            var existingOperators = await _operatorRepository.CountAsync();

            if (existingFields > 0 && existingOperators > 0)
            {
                _logger.LogInformation("元数据已存在，跳过初始化");
                return;
            }

            // 初始化字段定义
            await InitializeFieldDefinitionsAsync();

            // 初始化操作符定义
            await InitializeOperatorDefinitionsAsync();

            _logger.LogInformation("默认元数据初始化完成");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化默认元数据时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 初始化字段定义
    /// </summary>
    private async Task InitializeFieldDefinitionsAsync()
    {
        var fieldDefinitions = new List<FieldDefinition>
        {
            // 患者基本信息
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "patient.age",
                Path = "patient.age",
                DisplayName = "患者年龄",
                Description = "患者的年龄（岁）",
                DataType = "number",
                Category = "患者信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 1
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "patient.gender",
                Path = "patient.gender",
                DisplayName = "患者性别",
                Description = "患者的性别",
                DataType = "string",
                Category = "患者信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "in", "notin" }),
                ConfigJson = JsonSerializer.Serialize(new {
                    options = new[] {
                        new { value = "male", label = "男" },
                        new { value = "female", label = "女" }
                    }
                }),
                Order = 2
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "patient.weight",
                Path = "patient.weight",
                DisplayName = "患者体重",
                Description = "患者的体重（公斤）",
                DataType = "number",
                Category = "患者信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 3
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "patient.height",
                Path = "patient.height",
                DisplayName = "患者身高",
                Description = "患者的身高（厘米）",
                DataType = "number",
                Category = "患者信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 4
            },
            
            // 诊断信息
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "diagnosis.primary",
                Path = "diagnosis.primary",
                DisplayName = "主要诊断",
                Description = "患者的主要诊断",
                DataType = "string",
                Category = "诊断信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "contains", "startswith", "endswith", "in", "notin" }),
                Order = 1
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "diagnosis.secondary",
                Path = "diagnosis.secondary",
                DisplayName = "次要诊断",
                Description = "患者的次要诊断列表",
                DataType = "array",
                Category = "诊断信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "contains", "in", "notin" }),
                Order = 2
            },
            
            // 药物信息
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "medication.name",
                Path = "medication.name",
                DisplayName = "药物名称",
                Description = "药物的通用名称",
                DataType = "string",
                Category = "药物信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "contains", "startswith", "endswith", "in", "notin" }),
                Order = 1
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "medication.dosage",
                Path = "medication.dosage",
                DisplayName = "药物剂量",
                Description = "药物的剂量（毫克）",
                DataType = "number",
                Category = "药物信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 2
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "medication.frequency",
                Path = "medication.frequency",
                DisplayName = "用药频次",
                Description = "每日用药次数",
                DataType = "number",
                Category = "药物信息",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte" }),
                Order = 3
            },
            
            // 检验结果
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "lab.bloodPressure.systolic",
                Path = "lab.bloodPressure.systolic",
                DisplayName = "收缩压",
                Description = "收缩压值（mmHg）",
                DataType = "number",
                Category = "检验结果",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 1
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "lab.bloodPressure.diastolic",
                Path = "lab.bloodPressure.diastolic",
                DisplayName = "舒张压",
                Description = "舒张压值（mmHg）",
                DataType = "number",
                Category = "检验结果",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 2
            },
            new FieldDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Name = "lab.bloodSugar",
                Path = "lab.bloodSugar",
                DisplayName = "血糖",
                Description = "血糖值（mmol/L）",
                DataType = "number",
                Category = "检验结果",
                IsRequired = false,
                IsConditionable = true,
                SupportedOperatorsJson = JsonSerializer.Serialize(new[] { "eq", "ne", "gt", "gte", "lt", "lte", "between" }),
                Order = 3
            }
        };

        await _fieldRepository.AddRangeAsync(fieldDefinitions);
        _logger.LogInformation("成功初始化 {Count} 个字段定义", fieldDefinitions.Count);
    }

    /// <summary>
    /// 初始化操作符定义
    /// </summary>
    private async Task InitializeOperatorDefinitionsAsync()
    {
        var operatorDefinitions = new List<OperatorDefinition>
        {
            // 等于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "eq",
                DisplayName = "等于",
                Description = "值相等比较",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string", "number", "boolean", "date" }),
                Category = "比较",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} == {value}",
                Order = 1
            },
            // 不等于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "ne",
                DisplayName = "不等于",
                Description = "值不相等比较",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string", "number", "boolean", "date" }),
                Category = "比较",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} != {value}",
                Order = 2
            },
            // 大于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "gt",
                DisplayName = "大于",
                Description = "数值大于比较",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "number", "date" }),
                Category = "比较",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} > {value}",
                Order = 3
            },
            // 大于等于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "gte",
                DisplayName = "大于等于",
                Description = "数值大于等于比较",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "number", "date" }),
                Category = "比较",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} >= {value}",
                Order = 4
            },
            // 小于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "lt",
                DisplayName = "小于",
                Description = "数值小于比较",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "number", "date" }),
                Category = "比较",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} < {value}",
                Order = 5
            },
            // 小于等于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "lte",
                DisplayName = "小于等于",
                Description = "数值小于等于比较",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "number", "date" }),
                Category = "比较",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} <= {value}",
                Order = 6
            },
            // 包含
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "contains",
                DisplayName = "包含",
                Description = "字符串包含检查",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string", "array" }),
                Category = "文本",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field}.Contains({value})",
                Order = 7
            },
            // 开始于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "startswith",
                DisplayName = "开始于",
                Description = "字符串开始于检查",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string" }),
                Category = "文本",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field}.StartsWith({value})",
                Order = 8
            },
            // 结束于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "endswith",
                DisplayName = "结束于",
                Description = "字符串结束于检查",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string" }),
                Category = "文本",
                RequiresValue = true,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field}.EndsWith({value})",
                Order = 9
            },
            // 在列表中
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "in",
                DisplayName = "在列表中",
                Description = "值在指定列表中",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string", "number", "boolean" }),
                Category = "集合",
                RequiresValue = true,
                SupportsMultipleValues = true,
                ExpressionTemplate = "{value}.Contains({field})",
                Order = 10
            },
            // 不在列表中
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "notin",
                DisplayName = "不在列表中",
                Description = "值不在指定列表中",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "string", "number", "boolean" }),
                Category = "集合",
                RequiresValue = true,
                SupportsMultipleValues = true,
                ExpressionTemplate = "!{value}.Contains({field})",
                Order = 11
            },
            // 介于
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "between",
                DisplayName = "介于",
                Description = "值在指定范围内",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "number", "date" }),
                Category = "范围",
                RequiresValue = true,
                SupportsMultipleValues = true,
                ExpressionTemplate = "{field} >= {value1} && {field} <= {value2}",
                Order = 12
            },
            // 为空
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "isnull",
                DisplayName = "为空",
                Description = "值为空或null",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "*" }),
                Category = "空值",
                RequiresValue = false,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} == null",
                Order = 13
            },
            // 不为空
            new OperatorDefinition
            {
                Id = Guid.NewGuid().ToString(),
                Code = "isnotnull",
                DisplayName = "不为空",
                Description = "值不为空且不为null",
                SupportedDataTypesJson = JsonSerializer.Serialize(new[] { "*" }),
                Category = "空值",
                RequiresValue = false,
                SupportsMultipleValues = false,
                ExpressionTemplate = "{field} != null",
                Order = 14
            }
        };

        await _operatorRepository.AddRangeAsync(operatorDefinitions);
        _logger.LogInformation("成功初始化 {Count} 个操作符定义", operatorDefinitions.Count);
    }

    /// <summary>
    /// 获取数据类型定义
    /// </summary>
    /// <returns>数据类型定义集合</returns>
    private static List<DataTypeDefinition> GetDataTypeDefinitions()
    {
        return new List<DataTypeDefinition>
        {
            new DataTypeDefinition
            {
                Code = "string",
                DisplayName = "字符串",
                Description = "文本类型数据",
                               DefaultValue = "",
                ValidationRules = new { maxLength = 255 }
            },
            new DataTypeDefinition
            {
                Code = "number",
                DisplayName = "数字",
                Description = "数值类型数据",
                DefaultValue = 0,
                ValidationRules = new { min = double.MinValue, max = double.MaxValue }
            },
            new DataTypeDefinition
            {
                Code = "boolean",
                DisplayName = "布尔值",
                Description = "真/假类型数据",
                DefaultValue = false,
                ValidationRules = new { }
            },
            new DataTypeDefinition
            {
                Code = "date",
                DisplayName = "日期",
                Description = "日期时间类型数据",
                DefaultValue = DateTime.Now,
                ValidationRules = new { format = "yyyy-MM-dd" }
            },
            new DataTypeDefinition
            {
                Code = "array",
                DisplayName = "数组",
                Description = "数组类型数据",
                DefaultValue = new object[] { },
                ValidationRules = new { maxItems = 100 }
            },
            new DataTypeDefinition
            {
                Code = "object",
                DisplayName = "对象",
                Description = "对象类型数据",
                DefaultValue = new { },
                ValidationRules = new { }
            }
        };
    }

    /// <summary>
    /// 获取动作类型定义
    /// </summary>
    /// <returns>动作类型定义集合</returns>
    private static List<ActionTypeDefinition> GetActionTypeDefinitions()
    {
        return new List<ActionTypeDefinition>
        {
            new ActionTypeDefinition
            {
                Code = "log",
                DisplayName = "记录日志",
                Description = "记录规则执行日志",
                Icon = "📝",
                ConfigTemplate = new
                {
                    level = "info",
                    message = "规则执行成功",
                    includeContext = true
                }
            },
            new ActionTypeDefinition
            {
                Code = "notification",
                DisplayName = "发送通知",
                Description = "发送邮件、短信或推送通知",
                Icon = "📧",
                ConfigTemplate = new
                {
                    type = "email",
                    recipients = new[] { "" },
                    subject = "",
                    message = "",
                    template = ""
                }
            },
            new ActionTypeDefinition
            {
                Code = "dataupdate",
                DisplayName = "更新数据",
                Description = "更新数据库或调用API",
                Icon = "💾",
                ConfigTemplate = new
                {
                    target = "database",
                    table = "",
                    fields = new { },
                    condition = ""
                }
            },
            new ActionTypeDefinition
            {
                Code = "workflow",
                DisplayName = "触发工作流",
                Description = "触发其他工作流或规则",
                Icon = "🔄",
                ConfigTemplate = new
                {
                    workflowName = "",
                    parameters = new { },
                    async = true
                }
            },
            new ActionTypeDefinition
            {
                Code = "validation",
                DisplayName = "数据验证",
                Description = "验证数据完整性和有效性",
                Icon = "✅",
                ConfigTemplate = new
                {
                    rules = new[] { "" },
                    onFailure = "stop",
                    errorMessage = ""
                }
            },
            new ActionTypeDefinition
            {
                Code = "calculation",
                DisplayName = "数据计算",
                Description = "执行数学计算或数据转换",
                Icon = "🧮",
                ConfigTemplate = new
                {
                    expression = "",
                    outputField = "",
                    precision = 2
                }
            },
            new ActionTypeDefinition
            {
                Code = "alert",
                DisplayName = "系统警报",
                Description = "生成系统警报或异常提醒",
                Icon = "🚨",
                ConfigTemplate = new
                {
                    level = "warning",
                    message = "",
                    category = "",
                    autoResolve = false
                }
            }
        };
    }

    /// <summary>
    /// 获取优先级定义
    /// </summary>
    /// <returns>优先级定义集合</returns>
    private static List<PriorityDefinition> GetPriorityDefinitions()
    {
        return new List<PriorityDefinition>
        {
            new PriorityDefinition
            {
                Value = 1,
                DisplayName = "关键",
                Color = "#ff4d4f",
                Description = "最高优先级，必须立即执行"
            },
            new PriorityDefinition
            {
                Value = 2,
                DisplayName = "高",
                Color = "#ff7a45",
                Description = "高优先级，优先执行"
            },
            new PriorityDefinition
            {
                Value = 3,
                DisplayName = "中",
                Color = "#faad14",
                Description = "中等优先级，正常执行"
            },
            new PriorityDefinition
            {
                Value = 4,
                DisplayName = "低",
                Color = "#52c41a",
                Description = "低优先级，可延后执行"
            },
            new PriorityDefinition
            {
                Value = 5,
                DisplayName = "最低",
                Color = "#13c2c2",
                Description = "最低优先级，空闲时执行"
            }
        };
    }

    /// <summary>
    /// 获取分类定义
    /// </summary>
    /// <returns>分类定义集合</returns>
    private static List<CategoryDefinition> GetCategoryDefinitions()
    {
        return new List<CategoryDefinition>
        {
            new CategoryDefinition
            {
                Code = "patient",
                DisplayName = "患者管理",
                Icon = "👤",
                Color = "#1890ff",
                SubCategories = new List<CategoryDefinition>
                {
                    new CategoryDefinition
                    {
                        Code = "patient.basic",
                        DisplayName = "基本信息",
                        Icon = "📋",
                        Color = "#1890ff"
                    },
                    new CategoryDefinition
                    {
                        Code = "patient.medical",
                        DisplayName = "病史信息",
                        Icon = "🏥",
                        Color = "#1890ff"
                    }
                }
            },
            new CategoryDefinition
            {
                Code = "diagnosis",
                DisplayName = "诊断管理",
                Icon = "🔍",
                Color = "#52c41a",
                SubCategories = new List<CategoryDefinition>
                {
                    new CategoryDefinition
                    {
                        Code = "diagnosis.primary",
                        DisplayName = "主要诊断",
                        Icon = "🎯",
                        Color = "#52c41a"
                    },
                    new CategoryDefinition
                    {
                        Code = "diagnosis.differential",
                        DisplayName = "鉴别诊断",
                        Icon = "🔄",
                        Color = "#52c41a"
                    }
                }
            },
            new CategoryDefinition
            {
                Code = "medication",
                DisplayName = "药物管理",
                Icon = "💊",
                Color = "#faad14",
                SubCategories = new List<CategoryDefinition>
                {
                    new CategoryDefinition
                    {
                        Code = "medication.prescription",
                        DisplayName = "处方管理",
                        Icon = "📝",
                        Color = "#faad14"
                    },
                    new CategoryDefinition
                    {
                        Code = "medication.interaction",
                        DisplayName = "药物相互作用",
                        Icon = "⚠️",
                        Color = "#faad14"
                    },
                    new CategoryDefinition
                    {
                        Code = "medication.allergy",
                        DisplayName = "药物过敏",
                        Icon = "🚫",
                        Color = "#faad14"
                    }
                }
            },
            new CategoryDefinition
            {
                Code = "laboratory",
                DisplayName = "检验管理",
                Icon = "🧪",
                Color = "#722ed1",
                SubCategories = new List<CategoryDefinition>
                {
                    new CategoryDefinition
                    {
                        Code = "laboratory.blood",
                        DisplayName = "血液检验",
                        Icon = "🩸",
                        Color = "#722ed1"
                    },
                    new CategoryDefinition
                    {
                        Code = "laboratory.urine",
                        DisplayName = "尿液检验",
                        Icon = "🧫",
                        Color = "#722ed1"
                    },
                    new CategoryDefinition
                    {
                        Code = "laboratory.imaging",
                        DisplayName = "影像检查",
                        Icon = "📷",
                        Color = "#722ed1"
                    }
                }
            },
            new CategoryDefinition
            {
                Code = "safety",
                DisplayName = "安全管理",
                Icon = "🛡️",
                Color = "#ff4d4f",
                SubCategories = new List<CategoryDefinition>
                {
                    new CategoryDefinition
                    {
                        Code = "safety.dosage",
                        DisplayName = "剂量安全",
                        Icon = "⚖️",
                        Color = "#ff4d4f"
                    },
                    new CategoryDefinition
                    {
                        Code = "safety.contraindication",
                        DisplayName = "禁忌症检查",
                        Icon = "🚫",
                        Color = "#ff4d4f"
                    },
                    new CategoryDefinition
                    {
                        Code = "safety.monitoring",
                        DisplayName = "监测提醒",
                        Icon = "📊",
                        Color = "#ff4d4f"
                    }
                }
            },
            new CategoryDefinition
            {
                Code = "workflow",
                DisplayName = "流程管理",
                Icon = "🔄",
                Color = "#13c2c2",
                SubCategories = new List<CategoryDefinition>
                {
                    new CategoryDefinition
                    {
                        Code = "workflow.admission",
                        DisplayName = "入院流程",
                        Icon = "🏥",
                        Color = "#13c2c2"
                    },
                    new CategoryDefinition
                    {
                        Code = "workflow.discharge",
                        DisplayName = "出院流程",
                        Icon = "🚪",
                        Color = "#13c2c2"
                    },
                    new CategoryDefinition
                    {
                        Code = "workflow.transfer",
                        DisplayName = "转科流程",
                        Icon = "↔️",
                        Color = "#13c2c2"
                    }
                }
            }
        };
    }
}

